package com.baibei.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * 导航栏
 * Created by ChenRui on 2017/5/3 0003 14:45.
 */
public class Toolbar extends android.support.v7.widget.Toolbar {

    private TextView mTitleTextView;
    private CharSequence mTitleText;
    private final int[] location = new int[2];

    public Toolbar(Context context) {
        super(context);
        initView();
    }

    public Toolbar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public Toolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {

    }


    @Override
    public void setTitle(CharSequence title) {
        if (!TextUtils.isEmpty(title)) {
            if (mTitleTextView == null) {
                mTitleTextView = (TextView) findViewById(android.R.id.title);
            }
        }

        if (mTitleTextView != null) {
            mTitleTextView.setText(title);
        }

        mTitleText = title;
    }

    @Override
    public CharSequence getTitle() {
        return mTitleText;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

        if (mTitleTextView == null) return;

        // 标题居中显示
        int height = mTitleTextView.getMeasuredHeight(); // 高度
        int width = mTitleTextView.getMeasuredWidth(); // 宽度

        int titleLeft = getMeasuredWidth() / 2 - width / 2; // 左边位置
        int titleTop = getMeasuredHeight() / 2 - height / 2; // 顶部位置
        int titleRight = titleLeft + width;
        int titleBottom = titleTop + height;

        mTitleTextView.layout(titleLeft, titleTop, titleRight, titleBottom);

    }

    public void hideHomeAsUp() {
        setNavigationIcon(new ColorDrawable(Color.TRANSPARENT));
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if ((getContext() instanceof Activity)) {
            Activity activity = ((Activity) getContext());
            CharSequence title = activity.getTitle();
            setTitle(title);
        }
    }
}
